package com.lst.projectlib.util;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.lst.projectlib.R;
import com.lst.projectlib.dialog.CaptureDialog;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;

public class SelectImageUtil {
	public static final int REQUEST_CROP = 2000;
	public static final int REQUEST_CAPTURE = 2001;
	public static final int REQUEST_PICK = 2002;
	public static final int REQUEST_PICK_CUSTOM = 2003;
	public static final int REQUEST_HANDLER_ID = 2004;

	private Activity activity;
	private String saveFilePath = "";//拍照后裁剪之后的图片保存的路径
	private CaptureDialog captureDialog;//选择图片来源的弹出框
	private File mTmpFile;//拍照后图片的路径,只保存最后一次拍照的路径
	private Uri fileUri;//拍照后图片的路径uri地址,只保存最后一次拍照的路径
	private DisplayImageOptions.Builder builder;
	private Map<String,String> imageSelectMap = new LinkedHashMap<String,String>();//已选择的图片路径
	private Map<String,String> imageBase64Map = new LinkedHashMap<String,String>();//将已选择的图片路径处理过的列表

	public Map<String, String> getImageBase64Map() {
		return imageBase64Map;
	}
	public Map<String, String> getImageSelectMap() {
		return imageSelectMap;
	}

	/**
	 * 添加大图
	 * @param key
	 * @param handler
     */
	public void addImageSeledtMap(String key, Handler handler){
		addImageSelectMap(key, 540, 960, handler);
	}

	/**
	 * 添加用户头像
	 * @param key
	 * @param handler
	 */
	public void addHeaderImageSeledtMap(String key, Handler handler){
		addImageSelectMap(key, 240, 320, handler);
	}

	/**
	 * 添加图片
	 * @param key
	 * @param width
	 * @param height
     * @param handler
     */
	public void addImageSelectMap(String key, int width, int height, Handler handler){
		if(!TextUtils.isEmpty(key)){
			if (!key.startsWith("file://") && !key.startsWith("http://")) {
				key = ("file://" + key);
			}

			if(imageSelectMap.containsKey(key)){
			}else{
				imageSelectMap.put(key,key);
				imageBase64Map.put(key,"");
				//格式化图片为base64
				formatPicToBase64(Uri.parse(key), width, height, handler);
			}
		}
	}

	/**
	 * 删除图片
	 * @param key
	 * @param handler
     */
	public void removeImageSelectMap(String key, Handler handler){
		removeImageSelectMap(key, handler,true);
	}

	/**
	 * 删除图片并发送广播
	 * @param key
	 * @param handler
	 * @param isMinus
     */
	private void removeImageSelectMap(String key, Handler handler, boolean isMinus){
		if(!TextUtils.isEmpty(key)){
			imageSelectMap.remove(key);
			imageBase64Map.remove(key);

			if(isMinus){
				sendHandlerMsg(handler, -1);
			}else{
				sendHandlerMsg(handler, 0);
			}
		}
	}

	public Uri getFileUri() {
		return Uri.fromFile(mTmpFile);
	}

	public SelectImageUtil(Activity activity, String saveFilePath) {
		this.activity = activity;
		this.saveFilePath = saveFilePath;
		builder = ImageLoaderUtil.getInstance().getDisplayImageBuilder().cacheInMemory(false).cacheOnDisk(false);
	}

	/**
	 * 弹出选择图片来源的弹框
	 */
	public void showDialog() {
		if( captureDialog == null){
			captureDialog= new CaptureDialog(activity, R.style.progress_dialog,
					new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							int id = v.getId();
							if (id == R.id.tv_local_image) {
//								selectPicBySystemPick();
								selectPicByCustomPickSingle(false);
							} else if (id == R.id.tv_capture_image) {
								selectPicBySystemCapture();
							}
						}
					});
		}
		captureDialog.show();
	}

	/**
	 * 调启系统相册
	 */
	public void selectPicBySystemPick(){
		//一种是直接进入相册
		Intent intent = new Intent(Intent.ACTION_PICK,  MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		intent.setType("image/*");//这里的type, 设置类型(如:jpeg)之后没有任何作用

//		//另一种是直接进入相册目录
//		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//		intent.setType("image/jpeg");//这里的type, 设置类型(如:jpeg)之后有过滤作用的

		activity.startActivityForResult(intent, REQUEST_PICK);
	}

	/**
	 * 自定义相册之单选图片
	 * @param showCamera
     */
	public void selectPicByCustomPickSingle(boolean showCamera){
		selectPicByCustomPick(showCamera, false, 0, null);
	}

	/**
	 * 自定义相册之多选图片
	 * @param showCamera
	 * @param limitCount
	 * @param selectPath
     */
	public void selectPicByCustomPickMulti(boolean showCamera, int limitCount, ArrayList<String> selectPath){
		selectPicByCustomPick(showCamera,true,limitCount,selectPath);
	}

	/**
	 * 调启自定义的多选图片相册
	 * @param showCamera
	 * @param isMulti
	 * @param limitCount
	 * @param selectPath
     */
	private void selectPicByCustomPick(boolean showCamera, boolean isMulti, int limitCount, ArrayList<String> selectPath){
		MultiImageSelector selector = MultiImageSelector.create().showCamera(showCamera); // show camera or not. true by default
		if(isMulti){
			selector.count(limitCount); // max select image size, 9 by default. used width #.multi()
			selector.multi(); // multi mode, default mode;
			if(selectPath!=null){
				selector.origin(selectPath); // original select data set, used width #.multi()
			}
		}else{
			selector.single();
		}
		selector.start(activity, REQUEST_PICK_CUSTOM);
	}

	/**
	 * 调启系统相机
	 */
	public void selectPicBySystemCapture(){
		// 利用系统自带的相机应用:拍照
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// 判断存储卡是否可以用，可用进行存储
		if (SDCardUtil.hasSDcard()) {
			mTmpFile = FileUtil.getOutputFile(saveFilePath, System.currentTimeMillis() + ".jpg");
			if(Build.VERSION.SDK_INT < 24){
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
			}else{
				//android7.0及以后版本，不再支持通过 Intent 传递 “file://” scheme, 可以使用 content://传递
				ContentValues contentValues = new ContentValues(1);
				contentValues.put(MediaStore.Images.Media.DATA, mTmpFile.getAbsolutePath());
				Uri uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//这里的uri使用 content:// 的形式
			}
		} else {
			Toast.makeText(activity, "内存卡被拔出：头像图片等功能将暂时不可用！", Toast.LENGTH_SHORT).show();
			return;
		}
		activity.startActivityForResult(intent, REQUEST_CAPTURE);
	}

	/**
	 * 裁剪图片
	 * @param uri
     */
	public void setCropPic(Uri uri){
		UCrop uCrop = UCrop.of(uri, FileUtil.getOutputFileUri(saveFilePath, System.currentTimeMillis() + ".jpg"));
		uCrop.withAspectRatio(1, 1);//设置裁剪图片的宽高比

		UCrop.Options options = new UCrop.Options();//自定义方法
		options.setToolbarColor(ActivityCompat.getColor(activity, R.color.crop_page_titlebar));
		options.setStatusBarColor(ActivityCompat.getColor(activity, R.color.black));
		//最后别忘记调用
		uCrop.withOptions(options);

		uCrop.start(activity, REQUEST_CROP);
	}

	/**
	 * 保存裁剪之后的图片数据
	 */
	public Uri getCropPic(Intent data) {
		return UCrop.getOutput(data);
	}

	/**
	 * 将图片转换为base64
	 * @param uri
	 * @param handler
     */
	public void formatPicToBase64(Uri uri, final int width, final int height, final Handler handler){
		final String imgPath = uri.toString();
		if(TextUtils.isEmpty(imgPath)) return;

		new Thread(new Runnable() {
			@Override
			public void run() {
				Bitmap bitmap = ImageLoaderUtil.getInstance().loadImageSync(imgPath, width, height, builder);
				if(!isHaveKey(imgPath, bitmap, handler)) return; //在获取bitmap后
				//压缩方式1
				bitmap = BitmapUtil.compressFromBitmap(bitmap,width,height,200);
				if(!isHaveKey(imgPath, bitmap, handler)) return;//在压缩bitmap后

				String base64Str = Base64Util.bitmapToBase64(bitmap);
				if(!isHaveKey(imgPath, bitmap, handler)) return;//在转换bitmap后
				imageBase64Map.put(imgPath, base64Str);
				// 释放Bitmap
				if (bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
				}
				sendHandlerMsg(handler, 1);
			}
		}).start();
	}

	/**
	 * 发送handler消息
	 * @param handler
	 * @param isAddAction [-1, 0, 1]
     */
	private void sendHandlerMsg(Handler handler, int isAddAction){
		if (handler != null){
			Message msg = new Message();
			msg.what = REQUEST_HANDLER_ID;
			msg.obj = isAddAction;//判断是增加还是减少的操作
			handler.sendMessage(msg);
		}
	}

	/**
	 * 判断是否存在这个key
	 * @param imgPath
     * @return
     */
	private boolean isHaveKey(String imgPath, Bitmap bitmap, Handler handler){
		boolean isHaveKey = imageBase64Map.containsKey(imgPath);
		if(!isHaveKey){ //先判断是否已经手动删除了该key
			// 释放Bitmap
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
			}
			sendHandlerMsg(handler, 1);
		}else{
			if(bitmap==null){ //否则，判断bitmap是否为null
				removeImageSelectMap(imgPath,handler,false);
				isHaveKey = imageBase64Map.containsKey(imgPath);
			}
		}

		return isHaveKey;
	}

	/**
	 * 拍照完之后，如果需要系统图库显示，必须刷新一下
	 */
	public void refreshSystemPick(Uri fileUri){
		// 扫描图片到图库
		activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
	}

//	/**
//	 * 硬件压缩,需要引用bither-compress的module
//	 * @param imgPath
//	 * @param bitmap
//     */
//	private void compressImage(String imgPath, Bitmap bitmap){
//		File jpegTrueFile = FileUtil.getOutputFile("/image","compress_"+ System.currentTimeMillis() +".jpg");
//		Log.e("gyb", "====开始==压缩==saveFile==" + jpegTrueFile.getAbsolutePath());
//		NativeUtil.compressBitmap(bitmap, jpegTrueFile.getAbsolutePath());
//		Log.e("gyb", "====完成==压缩==saveFile==" + jpegTrueFile.getAbsolutePath());
//		// 释放Bitmap
//		if (bitmap != null && !bitmap.isRecycled()) {
//			bitmap.recycle();
//		}
//		try {
//			String base64Str = Base64Util.encodeBase64File(jpegTrueFile.getAbsolutePath());
//			if(!TextUtils.isEmpty(base64Str)){
//				Log.e("gyb", "====成功将文件转换为Base64Str====");
//				imageBase64Map.put(imgPath, Base64Util.bitmapToBase64(bitmap));
//			}else{
//				Log.e("gyb", "====将文件转换为Base64Str失败====");
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			Log.e("gyb", "====将文件转换为Base64Str失败====" + e.toString());
//		} finally {
//			FileUtil.delete(jpegTrueFile);
//			Log.e("gyb", "====删除文件====");
//		}
//	}
}
